import type { UserInfo } from '@vben/types';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { changePasswordApi } from '#/api/core/user';
import { ElMessage } from 'element-plus';

interface State {
  userInfo: UserInfo | null;
}

interface Actions {
  setUserInfo(info: UserInfo | null): void;
  changePassword(params: { oldPassword: string; newPassword: string }): Promise<boolean>;
  $reset(): void;
}

export const useUserStore = defineStore('core-user', () => {
  const userInfo = ref<UserInfo | null>(null);

  function setUserInfo(info: UserInfo | null) {
    userInfo.value = info;
  }

  /**
   * 修改密码
   * @param params 密码参数
   */
  async function changePassword(params: {
    oldPassword: string;
    newPassword: string;
  }): Promise<boolean> {
    try {
      await changePasswordApi(params);
      ElMessage.success('密码修改成功');
      return true;
    } catch (error: any) {
      ElMessage.error(error.message || '密码修改失败');
      return false;
    }
  }

  function $reset() {
    userInfo.value = null;
  }

  return {
    userInfo,
    setUserInfo,
    changePassword,
    $reset,
  };
});

export type UserStore = State & Actions;
